package com.ruoyi.web.controller.app;

import com.ruoyi.canteen.domain.dto.UserDto;
import com.ruoyi.canteen.domain.dto.UserPostDto;
import com.ruoyi.canteen.mapper.MainMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DingDingUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 杨祥
 * @date: 2025/02/25/11:35
 * @description:
 */
@RestController
public class LoginController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private MainMapper mainMapper;

    @PostMapping("/dingLogin")
    public AjaxResult login(@RequestParam(value = "code") String requestAuthCode) throws Exception {
        // 1. 获取钉钉用户身份
        AjaxResult ajax = AjaxResult.success();
        String token = DingDingUtil.getToken();
        Map<String, String> ddUserInfo = DingDingUtil.getUserInfo(token, requestAuthCode);
        String nickName = ddUserInfo.get("name");
        String ddUserId = ddUserInfo.get("userId");
        // 2. 查询本地系统用户
        SysUser sysUser = userService.selectByDdUserId(ddUserId);
        if (sysUser == null) {
            UserDto dto = new UserDto();
            List<Long> departmentId = DingDingUtil.getDepartmentId(ddUserId, token);
            if(CollectionUtils.isEmpty(departmentId)){
                departmentId.add(100L);
            }
            String departmentName = DingDingUtil.getDepartmentName(departmentId.get(0).toString(), token);
            Map<String, Long> deptNameToIdMap = getDeptNameToIdMap();
            Long deptId = deptNameToIdMap.get(departmentName);
            Map<String, String> userInfoDetail = DingDingUtil.getUserInfoDetail(token, ddUserId);
            String userName = userInfoDetail.get("userName");
            if(StringUtils.isBlank(userName)){
                userName=nickName;
            }
            dto.setDeptId(deptId);
            dto.setUserName(userName);
            dto.setNickName(nickName);
            dto.setUserType("00");
            dto.setSex("0");
            dto.setPassword("$2a$10$80O5W0EBf.UOxgWJCDGTz.WJr66d0jmv5Nbw1uezZF8QBUOqCY16u");
            dto.setStatus("0");
            dto.setDelFlag("0");
            dto.setCreateBy("admin");
            dto.setCreateTime(new Date());
            dto.setUpdateBy("admin");
            dto.setUpdateTime(new Date());
            dto.setRemark(nickName);
            dto.setCount(30);
            dto.setDdUserId(ddUserId);
            mainMapper.insertUserByAutoCreate(dto);
            Map<String, Long> postMap = getPostMap();
            String postName = userInfoDetail.get("postName");
            Long postId = postMap.get(postName);
            mainMapper.inserUserpost(postId,dto.getId());
            return AjaxResult.error("该账号未绑定钉钉userId,现已自动绑定，刷新页面或者重进页面即可登录");
        }
        // 3. 创建Spring Security认证对象
        UserDetails userDetails = createLoginUser(sysUser);
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        // 4. 手动注入Security上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String tokenServiceToken = tokenService.createToken((LoginUser)userDetails);
        ajax.put(Constants.TOKEN, tokenServiceToken);
        return ajax;
    }
    private Map<String,Long> getPostMap(){
        Map<String, Long> postMap =new HashMap<>();
        List<UserPostDto> userPostDtos = mainMapper.getUserPostList();
        if(!CollectionUtils.isEmpty(userPostDtos)){
            for(UserPostDto userPostDto : userPostDtos){
                postMap.put(userPostDto.getpostName(),userPostDto.getPostId());
            }
        }
        return postMap;
    }
    public static Map<String, Long> getDeptNameToIdMap() {
        Map<String, Long> map = new HashMap<>();
        // 模拟从数据库查出来的内容，生产环境中应使用数据库查询
        map.put("苏州千机智能技术有限公司", 100L);
        map.put("行政中心", 101L);
        map.put("销售与市场中心", 200L);
        map.put("工业软件事业部", 201L);
        map.put("高端制造事业部", 202L);
        map.put("财务中心", 203L);
        map.put("供应链中心", 204L);
        map.put("人力资源中心", 205L);
        map.put("质量中心", 206L);
        map.put("软件测试部", 207L);
        map.put("CAM软件开发部", 208L);
        map.put("软件应用部", 209L);
        map.put("自适应软件开发部", 210L);
        map.put("工艺技术部", 211L);
        map.put("生产管理部", 212L);
        map.put("项目管理部", 213L);
        map.put("高端制造质量管理部", 214L);
        map.put("体系与精益改善部", 215L);
        return map;
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
